import requests
from lxml import etree
from bs4 import BeautifulSoup

base_url = "https://www.medchemexpress.cn"


def get_code(code):
    """货号处理"""
    try:
        return code.split('-')[0] + '-' + code.split('-')[1]
    except IndexError:
        print(f"货号格式错误{code}")


def search_procode(procode):
    """搜索货号信息
    """
    headers = {
        "Accept":
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Language":
        "zh-CN,zh;q=0.9",
        "Connection":
        "keep-alive",
        "Referer":
        "https://www.medchemexpress.cn/",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    }
    url = "https://www.medchemexpress.cn/search.html"
    params = {
        "q": procode,
    }
    response = requests.get(url, headers=headers, params=params)
    soup = BeautifulSoup(response.text, 'html.parser')
    result_dom = soup.find('ul', class_='srh_rst_list_con')
    # 找到指定的<dt>标签
    dt_tag = result_dom.find_all('dt', class_='s_pro_list_cat')
    for dt in dt_tag:
        a_tag = dt.find('a')
        if a_tag.get_text(strip=True) == procode:
            page_url = base_url + a_tag['href']
            print(page_url)
            return page_url
    return None

def get_sku_info(page_url):
    """获取商品sku信息"""
    headers = {
        "Accept":
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Language":
        "zh-CN,zh;q=0.9",
        "Connection":
        "keep-alive",
        "Referer":
        "https://www.medchemexpress.cn/",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    }
    response = requests.get(page_url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    table_dom = soup.find('table', class_='price_tbl')
    tr_dom = table_dom.find_all('tr')

    # 表格第一行表头为th,从第二行开始为td
    sku_list = []
    for tr in tr_dom[1:]:
        td_dom = tr.find_all('td')
        
        try:
            # 判断是否在售
            if td_dom[2].get_text(strip=True) == 'In-stock':
                sku_list.append({
                    'spec':
                    td_dom[0].get_text(strip=True),
                    'price':
                    td_dom[1].get_text(strip=True).replace('￥', ''),
                    'delivery_date':
                    td_dom[2].get_text(strip=True),
                })
                
        except IndexError:
            print("索引超出范围")
            


if __name__ == "__main__":
    pro_code = 'HY-P0266A'
    # pro_code = 'HY-N4302'
    url = search_procode(pro_code)
    if url: # 商品存在
        sku_list = get_sku_info(url)
        if sku_list: # 商品在售
            print(sku_list)
        else:
            print(f"【商品停售】{pro_code}") 
    else:
        print(f"【商品失效】{pro_code}")
